<?php

namespace App\Http\Middleware;

use App\Models\Admin\Role;
use App\Models\Admin\Rule;
use Closure, Route, Auth;

class Permission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $uri = "/" . Route::current()->uri;
        $user = Auth::guard('admin')->user();
        $role = Role::find($user->role_id);
        $userRule = $role->rule_ids;
        $userRuleArr = explode(',', $userRule);
        $userRuleArr = array_filter($userRuleArr);
        $userRules = Rule::whereIn('id', $userRuleArr)->select(['url'])->get()->toArray();
        $userRules = array_column($userRules, 'url');

        if ($user->id == 1) {
            // 超管绕过权限验证
            return $next($request);
        }

        if ($user->status != 1 || $role->status != 1) {
            $type = $user->status == 1 ? '角色' : '用户';

            return $this->ajaxReturn("此{$type}已被禁用，请联系管理员");
        }

        if ($user->store_id != 21) {
            if (!in_array($uri, $userRules)) {
                return $this->ajaxReturn("无权限");
            }
        }

        return $next($request);
    }

    private function ajaxReturn($info)
    {
        return response()->json([
            'code' => 20001,
            'data' => ['info' => $info]
        ]);
    }
}
